package com.ylyq.ylxx.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName PythonUtil
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/10/20 17:22
 * @Version 1.0
 */
public class PythonUtil {
    public static String execPython(String filePath,String... argment){
//        String[] arguments = new String[] {"C:\\Users\\EDZ\\AppData\\Local\\Programs\\Python\\Python37\\python", "C:\\Users\\EDZ\\Desktop\\模型\\投放模型\\Dataexport.py"};
        try {
            List<String> arguments=new ArrayList<>();
            arguments.add("C:\\Users\\EDZ\\AppData\\Local\\Programs\\Python\\Python37\\python");
            arguments.add(filePath);
            arguments.addAll(Arrays.asList(argment.clone()));

            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
            StringBuilder result=new StringBuilder();
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                result.append(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功，
            //返回值为1表示调用python脚本失败，这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            System.out.println(re);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
